package com.leyou.item.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.pojo.CategoriesVo;
import com.leyou.item.pojo.Category;
import org.aspectj.weaver.ast.Var;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.slf4j.Logger;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryService {

    private static final String CATEGORY_KEY_PRFIX = "category:pid:";
    private static final String CHILD_CATEGORY_KEY_PREFIX = "category:two_three:pid:";
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    private static final Logger logger= LoggerFactory.getLogger(CategoryService.class);

    public List<Category> queryByPid(Long pid) throws Exception {
        Category category = new Category();
        category.setParentId(pid);
        List<Category> categories;
        String jsonCategories = this.redisTemplate.opsForValue().get(CATEGORY_KEY_PRFIX + pid);
        if(!StringUtils.isEmpty(jsonCategories))
        {
            categories= objectMapper.readValue(jsonCategories,new TypeReference<List<Category>>(){});
            return categories;
        }
        // 如果没有，查询数据库
        categories = this.categoryMapper.select(category);
        if(!CollectionUtils.isEmpty(categories)){
            String value = objectMapper.writeValueAsString(categories);
            this.redisTemplate.opsForValue().set(CATEGORY_KEY_PRFIX+pid,value);

        }
        return categories;
    }

    public List<String> queryNamesByCids(List<Long> ids){

        List<String> names = new ArrayList<>();
        ids.forEach(id->{
            Category category = this.categoryMapper.selectByPrimaryKey(id);
            names.add(category.getName());
        });
        return names;
    }


    public List<Category> queryChild(Long id) {

        Category category = new Category();
        category.setParentId(id);
        List<Category>  categories = this.categoryMapper.select(category);
        return categories;


    }

    public List<CategoriesVo> querychildListByPid(Long pid) {

        // 存放商品的二级类目集合
        List<CategoriesVo> categoriesVoList;
        String jsonChildCategories = this.redisTemplate.opsForValue().get(CHILD_CATEGORY_KEY_PREFIX + pid);
        if(!StringUtils.isEmpty(jsonChildCategories))
        {
            try {
                categoriesVoList=objectMapper.readValue(jsonChildCategories,new TypeReference<List<CategoriesVo>>(){});
                return categoriesVoList;
            } catch (Exception e) {
                logger.error("解析缓存中的数据出错："+pid);
                e.printStackTrace();
            }
        }
        // 根据id查询二级类目
        Category record = new Category();
        record.setParentId(pid);
        List<Category> list=this.categoryMapper.select(record);
        List<CategoriesVo> categoriesVos= new ArrayList<>();
        list.forEach(category->{
            Long id=category.getId();
            Category category1 = new Category();
            category1.setParentId(id);
            CategoriesVo categoriesVo = new CategoriesVo();
            // 根据id查询三级类目
            List<Category> list1 = this.categoryMapper.select(category1);

            BeanUtils.copyProperties(category,categoriesVo);
            categoriesVo.setCategories(list1);
            categoriesVos.add(categoriesVo);
        });
         if(!StringUtils.isEmpty(categoriesVos))
         {
             try {
                 String value = objectMapper.writeValueAsString(categoriesVos);
                 this.redisTemplate.opsForValue().set(CHILD_CATEGORY_KEY_PREFIX+pid,value);
             } catch (JsonProcessingException e) {
                 logger.error("写入缓存中的数据出错："+pid);
                 e.printStackTrace();
             }
         }

             return categoriesVos;
    }
}
